<template>
  <ElementDialog
    ref="dialog"
    embed
    :visible="visible"
    :title="!form.id ? '新建采购订单' : '修改采购订单'"
    width="80%"
    :body-padding="false"
    height="500px"
    @close="closeDialog"
    @open="handleOpenBefore">
    <template #default>
      <ElForm
        ref="form"
        :disabled="disabled"
        :label-position="labelPosition"
        label-width="90px"
        :model="form"
        style="height: 100%">
        <NavTabPanel>
          <ElTabPane class="my-panel" style="padding: 10px" label="基本信息">
            <ElRow>
              <ElCol :span="8">
                <ElFormItem label="单号">
                  <ElInput v-model="form.caseid" :disabled="true" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="采购单位" prop="deptId" :rules="[{ required: true, message: '请输入采购单位！' }]">
                  <FyInputTree
                    v-model="form.deptId"
                    :dic="form.dictOption.deptTreeList"
                    :props="props"
                    placeholder="选择采购单位" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="采购人">
                  <ElInput v-model="form.createBy" :disabled="true" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol :span="8">
                <ElFormItem label="订购时间">
                  <ElDatePicker
                    v-model="form.orderDatetime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择订购时间"
                    align="right" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="到货时间">
                  <ElDatePicker
                    v-model="form.arrivalDatetime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择到货时间"
                    align="right" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="合同或发票" label-width="90px">
                  <ElSelect v-model="form.contractId" clearable placeholder="请选择合同或发票">
                    <ElOption
                      v-for="item in form.dictOption.contractTreeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id" />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol :span="8">
                <ElFormItem label="状态" prop="status" :rules="[{ required: true, message: '请选择状态！' }]">
                  <ElSelect v-model="form.status" clearable placeholder="请选择">
                    <ElOption
                      v-for="item in form.dictOption.statusList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value" />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="供应商" prop="supplierId" :rules="[{ required: true, message: '请选择供应商！' }]">
                  <ElSelect v-model="form.supplierId" clearable placeholder="请选择供应商！">
                    <ElOption
                      v-for="item in form.dictOption.supplierTreeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id" />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="采购方式">
                  <ElSelect v-model="form.method" clearable placeholder="请选择">
                    <ElOption
                      v-for="item in form.dictOption.purchaseWayList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value" />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol :span="8">
                <ElFormItem label="购置金额">
                  <ElInputNumber
                    v-model="form.amount"
                    controls-position="right"
                    disabled
                    :min="0"
                    :max="9999999999999"
                    label="订单金额" />
                </ElFormItem>
              </ElCol>
              <ElCol :span="8">
                <ElFormItem label="货币类型">
                  <ElSelect v-model="form.currencyType" clearable placeholder="请选择">
                    <ElOption
                      v-for="item in form.dictOption.currencyTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value" />
                  </ElSelect>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol :span="24">
                <ElFormItem label="收货信息">
                  <ElInput v-model="form.receivinfo" type="textarea" show-word-limit row="3" maxlength="2000" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol :span="24">
                <ElFormItem label="订单说明">
                  <ElInput v-model="form.explains" type="textarea" show-word-limit row="3" maxlength="2000" />
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol :span="24">
                <ElRow>
                  <ElCol :span="16">
                    <p style="padding: 0 10px">申请明细-物品列表</p>
                  </ElCol>
                  <ElCol :span="8">
                    <ElButton type="primary" class="el-icon-circle-plus" @click="selectApply"> 从申请单选择 </ElButton>
                    <ElButton type="primary" class="el-icon-circle-plus" @click="addCard">添加</ElButton>
                    <ElButton type="primary" class="el-icon-delete" @click="del">删除所选</ElButton>
                  </ElCol>
                </ElRow>
                <ElTable
                  v-if="!disabled"
                  :data="rows"
                  border
                  style="width: 100%"
                  :summary-method="getSummaries"
                  show-summary
                  @cell-click="cellClick"
                  @selection-change="onChange">
                  <ElTableColumn type="selection" width="55" />
                  <ElTableColumn prop="name" label="名称" />
                  <ElTableColumn prop="model" label="规格型号" width="120" />
                  <ElTableColumn prop="unit" label="计量单位" width="120" />
                  <ElTableColumn prop="price" label="单价" width="80" />
                  <ElTableColumn prop="quantity" label="申请数量" width="120">
                    <template #default="scope">
                      <ElInput
                        v-if="scope.row.quantityShow"
                        v-model="scope.row.quantity"
                        @blur="loseFocus(scope.$index, scope.row, scope.column)" />
                      <span v-else style="margin-left: 10px">{{ scope.row.quantity }}</span>
                    </template>
                  </ElTableColumn>
                  <ElTableColumn prop="orderQuantity" label="*已购数量" width="120" label-class-name="quantity">
                    <template #default="scope">
                      <ElInput
                        v-if="scope.row.orderQuantityShow"
                        v-model="scope.row.orderQuantity"
                        @blur="loseFocus(scope.$index, scope.row, scope.column)" />
                      <span v-else style="margin-left: 10px">{{ scope.row.orderQuantity }}</span>
                    </template>
                  </ElTableColumn>
                  <ElTableColumn prop="purchasedQuantity" label="*采购数量" width="120" label-class-name="quantity">
                    <template #default="scope">
                      <ElInput
                        v-if="scope.row.purchasedQuantityShow"
                        v-model="scope.row.purchasedQuantity"
                        @blur="loseFocus(scope.$index, scope.row, scope.column)" />
                      <span v-else style="margin-left: 10px">{{ scope.row.purchasedQuantity }}</span>
                    </template>
                  </ElTableColumn>
                  <ElTableColumn prop="amount" label="金额" width="80">
                    <template #default="scope">
                      <ElInput
                        v-if="scope.row.amountShow"
                        v-model="scope.row.amount"
                        @blur="loseFocusAmount(scope.$index, scope.row, scope.column)" />
                      <span v-else style="margin-left: 10px">{{ scope.row.amount }}</span>
                    </template>
                  </ElTableColumn>
                  <ElTableColumn prop="parentCaseid" label="申请编号" width="120" />
                  <ElTableColumn prop="deptFullname" label="申请单位" width="120" />
                </ElTable>
                <ElTable
                  v-if="disabled"
                  :data="rows"
                  border
                  style="width: 100%"
                  :summary-method="getSummaries"
                  show-summary
                  @cell-click="cellClick"
                  @selection-change="onChange">
                  <ElTableColumn type="selection" width="55" />
                  <ElTableColumn prop="statusCn" label="状态" width="80" />
                  <ElTableColumn prop="name" label="名称" />
                  <ElTableColumn prop="model" label="规格型号" width="120" />
                  <ElTableColumn prop="name" label="编号" />
                  <ElTableColumn prop="unit" label="计量单位" width="120" />
                  <ElTableColumn prop="quantity" label="申请数量" width="120" />
                  <ElTableColumn prop="orderQuantity" label="已购数量" width="120" />
                  <ElTableColumn prop="purchasedQuantity" label="采购数量" width="120" />
                  <ElTableColumn prop="price" label="单价" width="80" />
                  <ElTableColumn prop="amount" label="金额" width="80" />
                  <ElTableColumn prop="parentCaseid" label="申请编号" width="120" />
                  <ElTableColumn prop="deptFullname" label="申请单位" width="120" />
                </ElTable>
              </ElCol>
            </ElRow>
            <AssetCardTable
              :visible.sync="isPickerShow"
              :in-type="type"
              :asset-card-id="purchaseOrderId"
              @confirm="onConfirm" />
            <SelectApplyListTable :join-purchaseorder="true" :visible.sync="tableVisible" @confirm="onApplyList" />
          </ElTabPane>
          <ElTabPane class="my-panel" label="附件信息">
            <UploadPage ref="UploadPage" :unique-code="uniqueCode" model="purchaseOrder" classify="purchaseOrder" />
          </ElTabPane>
        </NavTabPanel>
      </ElForm>
    </template>
    <template #footer>
      <ElButton type="primary" @click="dataFormSubmit">确 定</ElButton>
      <slot name="footer"></slot>
    </template>
  </ElementDialog>
</template>

<script>
  import { fetchList, addObj, putObj, edit } from '@/api/asset/fyassetpurchaseorder'
  import { delPurchaseOrderListObj } from '@/api/asset/fyassetpurchaseorderlist'

  export default {
    name: 'PurchaseOrderDialog',
    props: {
      visible: Boolean,
      purchaseOrderId: {
        type: String
      },
      disabled: {
        type: Boolean
      }
    },
    data() {
      return {
        isPickerShow: false,
        rows: [],
        uniqueCode: '',
        selectedRows: [],
        labelPosition: 'right',
        form: {
          amount: '',
          arrivalDatetime: '',
          batchnumber: '',
          caseid: '',
          contractId: '',
          contractName: '',
          contractNumber: '',
          createBy: '',
          createId: 1,
          createTime: '',
          currencyType: '人民币',
          delFlag: '',
          deptFullname: '',
          deptId: '',
          detailed: '',
          explains: '',
          id: '',
          method: '',
          orderDatetime: '',
          parentCaseid: '',
          parentId: '',
          purchaseOrderList: [],
          receivinfo: '',
          status: '0',
          supplierId: '',
          supplierName: '',
          tenantId: '',
          type: 'ALL',
          unid: '',
          updateBy: '',
          updateTime: '',
          dictOption: {
            contractTreeList: [],
            currencyTypeList: [],
            purchaseWayList: [],
            statusList: [],
            supplierTreeList: [],
            deptTreeList: []
          }
        },
        props: {
          value: 'id',
          label: 'name'
        },
        tableVisible: false,
        type: 'ALL'
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {},
      getPage(page) {
        return fetchList({ current: page.page, size: page.limit })
      },
      onConfirm(rows) {
        if (this.rows === null || this.rows.length <= 0) {
          this.rows = rows
          this.form.purchaseOrderList = this.rows
        } else {
          rows.forEach(row => {
            let flag = false
            this.rows.forEach(curRow => {
              if (row.sauId === curRow.sauId) {
                flag = true
              }
            })
            if (!flag) {
              this.form.purchaseOrderList.push(row)
            }
          })
          this.rows = this.form.purchaseOrderList
        }
      },
      onChange(rows) {
        this.selectedRows = rows
      },
      del() {
        const deleteIds = []
        this.selectedRows.forEach(row => {
          if (row.id > 0) {
            deleteIds.push(row.id)
          }
        })
        this.$confirm(`是否确认删除"${deleteIds.length} "条明细数据？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (deleteIds.length > 0) {
              delPurchaseOrderListObj(deleteIds)
            }
            this.rows = this.rows.filter(value => !this.selectedRows.includes(value))
            this.form.purchaseOrderList = this.form.purchaseOrderList.filter(
              value => !this.selectedRows.includes(value)
            )
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      },
      addCard() {
        this.isPickerShow = true
      },
      // 单击事件
      cellClick(row, column) {
        // 可编辑字段
        const showField = ['purchasedQuantity', 'orderQuantity', 'amount', 'remarks']
        if (showField.includes(column.property)) {
          this.$set(row, `${column.property}Show`, true)
        }
      },
      confirm() {},
      handleOpenBefore() {
        this.rows = []
        this.selectedRows = []
        if (this.purchaseOrderId) {
          edit(this.purchaseOrderId).then(response => {
            const resultObj = response.data.data
            this.form = resultObj
            this.form.unid = resultObj.unid
            this.uniqueCode = resultObj.unid
            this.type = resultObj.type
            this.rows = resultObj.purchaseOrderList
            this.$emit('refreshChange')
          })
        } else {
          // 初始化可选项。
          // createPurchaseOrder()
          //   .then(response => {
          //     const resultObj = response.data.data
          //     this.form = resultObj
          //     this.form.supplierId = ''
          //     this.type = resultObj.type
          //     this.form.unid = resultObj.unid
          //     this.uniqueCode = resultObj.unid
          //   })
          //   .catch(() => {})
        }
      },
      dataFormSubmit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (this.rows === null || this.rows.length <= 0) {
              this.$message.warning('请选择物品列表！')
              return
            }

            if (this.rows.length > 0) {
              let checkStatus = false
              this.rows.forEach(row => {
                if (this.$isBlank(row.orderQuantity) || this.$isBlank(row.purchasedQuantity)) {
                  checkStatus = true
                }
              })
              if (checkStatus) {
                this.$message.warning('请输已购数量或采购数量！')
                return
              }
            }
            this.form.purchaseOrderList = this.rows
            if (valid) {
              const row = this.form
              this.form.dictOption = {}
              if (row.id) {
                putObj(row).then(data => {
                  this.$message.success('修改成功')
                  this.$refs.dialog.hide()
                  this.$emit('refreshDataList')
                })
              } else {
                addObj(row).then(data => {
                  this.$message.success('添加成功')
                  this.$refs.dialog.hide()
                  this.$emit('refreshDataList')
                })
              }
            }
          }
        })
      },
      loseFocus(index, row, column) {
        // 可编辑字段
        const showField = ['orderQuantity', 'purchasedQuantity', 'remarks']
        if (showField.includes(column.property)) {
          this.$set(row, `${column.property}Show`, false)
        }
      },
      loseFocusAmount(index, row, column) {
        const showField = ['amount']
        if (showField.includes(column.property)) {
          this.$set(row, `${column.property}Show`, false)
        }
        if (row.amount) {
          row.price = (row.amount / row.quantity).toFixed(4)
        }
      },
      closeDialog() {
        this.$refs.form.resetFields()
        this.form.deptId = -1
      },
      onApplyList(rows) {
        this.rows = rows
        this.form.purchaseOrderList = this.rows
        // 将采购申请 单的批次号和id赋值给采购订单
        if (rows.length > 0) {
          const row = rows[0]
          this.form.parentId = row.parentId
          this.form.parentCaseid = row.parentCaseid
          this.form.batchnumber = row.batchnumber
          this.type = row.type
          this.form.type = row.type
          this.form.supplierId = row.supplierId
          this.form.supplierName = row.supplierName
          this.form.currencyType = row.currencyType
          this.form.method = row.method
        }
      },
      selectApply() {
        this.tableVisible = true
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        const editPropertys = ['quantity', 'orderQuantity', 'purchasedQuantity', 'amount']
        columns.forEach((column, index) => {
          if (column.property === 'unit') {
            sums[index] = '总数量'
            return
          }
          if (column.property === 'price') {
            sums[index] = '总金额'
            return
          }
          if (editPropertys.includes(column.property)) {
            const values = data.map(item => Number(item[column.property]))
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ' '
            } else {
              sums[index] = '0'
            }
          }
        })
        return sums
      }
    }
  }
</script>

<style lang="scss">
  .el-table th > .cell.quantity {
    color: red;
    font-weight: normal;
    font-size: 12px;
  }
</style>
